package com.huishu.tcm.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.huishu.tcm.entity.User;
import com.huishu.tcm.service.UserService;
import com.huishu.tcm.util.AESUtil;
import com.huishu.tcm.util.Constants;
import com.huishu.tcm.util.exception.TcmException;
import com.huishu.tcm.util.exception.TcmExceptionEnum;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huishu.tcm.entity.Annex7;
import com.huishu.tcm.service.Annex7Service;
import com.huishu.tcm.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

@Api(tags = "附件7 糖尿病前期中医健康管理随访监测记录表")
@RestController
@RequestMapping("/api/annex7")
public class Annex7Controller extends BaseController<Annex7Service> {

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键查询一条数据", notes = "根据主键查询一条数据")
    @RequestMapping(method = RequestMethod.GET)
    public Annex7 get(@RequestParam String id) throws TcmException {
        QueryWrapper<Annex7> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        return service.getOne(wrapper);
    }

    /**
     * 查询数据列表
     * @return
     */
    @ApiOperation(value = "根据筛选条件查询数据列表", notes = "根据筛选条件查询数据列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public List<Annex7> list(@RequestBody Annex7 v) throws TcmException {
        QueryWrapper<Annex7> queryWrapper = service.getQueryWrapper(v);
        return service.list(queryWrapper);
    }

    /**
     * 分页查询数据列表
     * @param pageVo
     * @return
     */
    @ApiOperation(value = "根据筛选条件分页查询数据列表", notes = "根据筛选条件分页查询数据列表")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Page<Annex7> page(@RequestBody PageVo<Annex7> pageVo) throws TcmException {
        Annex7 v = pageVo.getEntity();
        QueryWrapper<Annex7> wrapper = service.getQueryWrapper(v);
        Page<Annex7> page = new Page<>(pageVo.getPage(),pageVo.getLimit());
        page = service.page(page,wrapper);
        return page;
    }

    /**
     * 添加
     * @param v
     * @return
     */
    @ApiOperation(value = "添加一条数据",notes = "添加一条数据")
    @RequestMapping(method = RequestMethod.POST)
    public boolean save(@RequestBody Annex7 v) throws Exception {
        QueryWrapper<Annex7> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_id",v.getPatientId());
        queryWrapper.orderByDesc("number");
        List<Annex7> list = service.list(queryWrapper);
        if(ObjectUtil.isEmpty(list)){
            v.setNumber(1);
        }else{
            v.setNumber(list.get(0).getNumber() + 1);
        }
        Date now = new Date();
        User loginUser = getLoginUser();
        v.setCreateTime(now);
        v.setCreateUser(loginUser.getName());
        v.setUpdateTime(now);
        v.setUpdateUser(loginUser.getName());
        return service.save(v);
    }

    /**
     * 根据主键更新
     * @param v
     * @return
     */
    @ApiOperation(value = "根据主键更新数据",notes = "根据主键更新数据")
    @RequestMapping(method = RequestMethod.PUT)
    public boolean update(@RequestBody Annex7 v) throws Exception {
        Date now = new Date();
        v.setUpdateTime(now);
        v.setUpdateUser(getLoginUser().getName());
        QueryWrapper<Annex7> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", v.getId());
        return service.update(v,queryWrapper);
    }


    /**
     * 根据主键删除
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键删除数据",notes = "根据主键删除数据")
    @RequestMapping(method = RequestMethod.DELETE)
    public boolean removeById(@RequestParam Integer id){
        QueryWrapper<Annex7> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return service.remove(wrapper);
    }

//    @Resource
//    UserService userService;

//    @ApiOperation(value = "根据医疗机构信息将糖尿病前期中医健康管理随访监测记录表导出到excel", notes="根据医疗机构信息将糖尿病前期中医健康管理随访监测记录表导出到excel")
//    @GetMapping(value = "/exportExcel", params = {"institutionId"})
//    public void exportExcel(Integer institutionId) throws TcmException, IOException {
//        // 根据医疗机构id查询患者列表
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("institution_id",institutionId);
//        userQueryWrapper.eq("role", Constants.USER_ROLE_PATIENT);
//        userQueryWrapper.orderByDesc("id");
//        List<User> patientList = userService.list(userQueryWrapper);
//        if(ObjectUtil.isEmpty(patientList)){
//            throw new TcmException(TcmExceptionEnum.DATA_NOT_EXISTS);
//        }
//        // 根据患者id列表查询 糖尿病前期中医健康管理随访监测记录 数据
//        List<Integer> patientIdList = patientList.stream().map(User::getId).collect(Collectors.toList());
//        QueryWrapper<Annex7> annex7QueryWrapper = new QueryWrapper<>();
//        annex7QueryWrapper.in("patient_id",patientIdList);
//        annex7QueryWrapper.orderByDesc("patient_id");
//        annex7QueryWrapper.orderByDesc("number");
//        List<Annex7> annex7List = service.list(annex7QueryWrapper);
//        if(ObjectUtil.isEmpty(annex7List)){
//            throw new TcmException(TcmExceptionEnum.DATA_NOT_EXISTS);
//        }
//        // 生成EXCEL数据
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        Sheet sheet = writer.getSheet();
//        List<List<String>> rows = new ArrayList<>();
//        List<String> row = CollUtil.newArrayList("姓名","性别","年龄","身份证号","手机号","是否了解改善生活方式对改善糖尿病前期有积极意义","教授的中医防病技巧是否能熟练运用","是否能熟练使用血糖仪自测血糖","是否注意合理膳食、均衡营养","是否按照“500111法则”或“手掌法则”执行情况","推荐中医食疗措施执行情况","有氧运动方式","有氧运动频次","有氧每次运动时长","阻抗运动方式","阻抗运动频次","阻抗每次运动时长","中医运动方式","中医运动频次","中医每次运动时长","其他中医运动管理措施执行情况","体重减轻","主动控制饮食","主动增强运动","中医减重执行情况","睡眠时间6-8小时","是否按处方落实调理","是否按照中医血糖控制处方严格执行","第几次录入");
//        rows.add(row);
//        for (User patient : patientList) {
//            AESUtil.userInfoDesensitization(patient);
//            for (Annex7 annex7: annex7List) {
//                if (annex7.getPatientId().equals(patient.getId())) {
//                    row = new ArrayList<>();
//                    row.add(patient.getName());
//                    row.add(patient.getGender());
//                    row.add(String.valueOf(patient.getAge()));
//                    row.add(patient.getIdNum());
//                    row.add(patient.getTelNum());
//                    row.add(annex7.getA211());
//                    row.add(annex7.getA212());
//                    row.add(annex7.getA213());
//                    row.add(annex7.getA221());
//                    row.add(annex7.getA222());
//                    row.add(annex7.getA223());
//                    row.add(annex7.getA231());
//                    row.add(annex7.getA232());
//                    row.add(annex7.getA233());
//                    row.add(annex7.getA234());
//                    row.add(annex7.getA235());
//                    row.add(annex7.getA236());
//                    row.add(annex7.getA237());
//                    row.add(annex7.getA238());
//                    row.add(annex7.getA239());
//                    row.add(annex7.getA2310());
//                    row.add(annex7.getA241());
//                    row.add(annex7.getA242());
//                    row.add(annex7.getA243());
//                    row.add(annex7.getA244());
//                    row.add(annex7.getA25());
//                    row.add(annex7.getA26());
//                    row.add(annex7.getA27());
//                    row.add(String.valueOf(annex7.getNumber()));
//                    rows.add(row);
//                }
//            }
//        }
//        writer.write(rows);
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        response.setHeader("Content-Disposition","attachment;filename=export.xlsx");
//        ServletOutputStream out = response.getOutputStream();
//        writer.flush(out, true);
//        writer.close();
//        IoUtil.close(out);
//    }

//    @ApiOperation(value = "查询本周是否填写个人报告", notes = "小程序端查询本周是否填写个人报告")
//    @GetMapping(value = "/queryIsReportThisWeek", params = {"patientId"})
//    public Boolean queryIsReportThisWeek(Integer patientId){
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE ,-7);
//        QueryWrapper<Annex7> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("patient_id",patientId);
//        queryWrapper.gt("create_time",sdf.format(calendar.getTime()));
//        List<Annex7> list = service.list(queryWrapper);
//        return ObjectUtil.isNotEmpty(list);
//    }
}